//
//  JKMediaLibraryViewController.m
//  Baisi
//
//  Created by albert on 2019/1/29.
//  Copyright © 2019 安永博. All rights reserved.
//

#import "JKMediaLibraryViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "JKFileExplorerEngine.h"
#import "JKFileManager.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>

@interface JKMediaLibraryViewController () <MPMediaPickerControllerDelegate>

@end

@implementation JKMediaLibraryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.title = @"媒体资料库";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    button.backgroundColor = [UIColor orangeColor];
    [button setTitle:@"mediaPicker" forState:(UIControlStateNormal)];
    
    button.frame = CGRectMake(15, 100, 100, 50);
    [self.view addSubview:button];
    
    [button addTarget:self action:@selector(showMediaPicker) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)showMediaPicker{
    
    MPMediaPickerController *picker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
    
    picker.prompt = @"添加本地音乐";
    
    picker.showsCloudItems = NO;
    
    picker.allowsPickingMultipleItems = YES;
    
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark
#pragma mark - MPMediaPickerControllerDelegate

- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{
    
    [mediaPicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
    
    for (MPMediaItem *item in [mediaItemCollection items]) {
        
        //打印输出消息
        
        NSLog(@"itemURL: %@ isFileURL: %d title: %@", item.assetURL, [item.assetURL isFileURL], item.title);
        
        [self convertMediaItemToMp3:item title:item.title directory:[JKFileManager documentsDirectory]];
        
        //[self saveWithURL:item.assetURL fileName:@""];
    }
    
    [mediaPicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveWithURL:(NSURL *)URL fileName:(NSString *)fileName{
    
    NSError *error = nil;
    NSData *fileData = [NSData dataWithContentsOfURL:URL options:NSDataReadingMappedIfSafe error:&error];
    
    if (error) {
        
        // 读取出错
        
    } else {
        
        NSString *filePath = [URL path];
        
        NSString *toPath = [[JKFileManager documentsDirectory] stringByAppendingPathComponent:[filePath lastPathComponent]];
        
        // 保存文件
        [JKFileExplorerEngine saveData:fileData toPath:toPath success:^(NSString *destinationPath) { // 保存成功
            
            NSLog(@"保存成功");
            
        } failure:^(NSString *destinationPath, NSError *error) { // 保存失败
            
            NSLog(@"保存失败");
        }];
    }
}

- (void)convertMediaItemToMp3:(MPMediaItem *)mediaItem title:(NSString *)title directory:(NSString *)directory{
    
    if (!mediaItem || !title || !directory) { return; }
    
    NSURL *url = [mediaItem valueForProperty:MPMediaItemPropertyAssetURL];
    
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    
    
    NSLog(@"compatible presets for songAsset: %@", [AVAssetExportSession exportPresetsCompatibleWithAsset:asset]);
    
    NSString *fileName = [title stringByAppendingString:@".m4a"];
    
    NSString *filePath = [directory stringByAppendingPathComponent:fileName];
    
    filePath = [JKFileExplorerEngine checkDuplicationNameWithFilePath:filePath isFolder:NO];
    
    
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetAppleM4A];
    
    NSLog (@"created exporter. supportedFileTypes: %@", exporter.supportedFileTypes);
    
    if (exporter.supportedFileTypes.count <= 0) {
        
        NSLog(@"No supportedFileTypes.");
        
        return;
    }
    
    exporter.outputFileType = exporter.supportedFileTypes.firstObject;//@"com.apple.m4a-audio";
    
    NSURL *exportURL = [NSURL fileURLWithPath:filePath] ;
    
    exporter.outputURL = exportURL;
    
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        
         AVAssetExportSessionStatus exportStatus = exporter.status;
         
         switch (exportStatus) {
             case AVAssetExportSessionStatusFailed: {
                 
                 // log error to text view
                 
                 NSError *exportError = exporter.error;
                 
                 NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
                 
                 break;
             }
             case AVAssetExportSessionStatusCompleted: {
                 
                 NSLog(@"currentThread-->%@", [NSThread currentThread]);
                 
                 NSLog (@"AVAssetExportSessionStatusCompleted");
                 
                 break;
             }
             case AVAssetExportSessionStatusUnknown: {
                 
                 NSLog (@"AVAssetExportSessionStatusUnknown");
                 
                 break;
                 
             }
             case AVAssetExportSessionStatusExporting: {
                 
                 NSLog (@"AVAssetExportSessionStatusExporting");
                 
                 break;
                 
             }
             case AVAssetExportSessionStatusCancelled: {
                 
                 NSLog (@"AVAssetExportSessionStatusCancelled");
                 
                 break;
                 
             }
             case AVAssetExportSessionStatusWaiting: {
                 
                 NSLog (@"AVAssetExportSessionStatusWaiting");
                 
                 break;
             }
             default:
             { NSLog (@"didn't get export status");
                 
                 break;
                 
             }
                 
         }
     }];
}
@end
